<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<body>
    <script>
        const list = [
            { id: 1, name: "部门1", pid: 0 }, // 根节点
            { id: 2, name: "部门2", pid: 1 },
            { id: 3, name: "部门3", pid: 1 },
            { id: 4, name: "部门4", pid: 3 },
            { id: 5, name: "部门5", pid: 4 },
        ];
        function listTree(list,pid,tree){
            list.forEach(item => {
                if(item.pid===pid){   //找根节点
                    tree.push(item)   //下一轮tree变成父节点的children数组
                }
            });
          //根节点找儿子 子的pid=父的id
            tree.forEach(item=>{
                item.children=[]  //定义一个数组接收儿子
                listTree(list,item.id,item.children)//找到的pid=父的id的数据放到children 是子节点
            })
            return tree
        }

         function listTree2(list,pid){
          let res=[]
          list.forEach(item=>{
            if(item.pid===pid){
                item.children=listTree2(list,item.id)  //找pid=id的项
                res.push(item)
            }
          })
          return res
         }


       console.log( listTree(list,0,[]))
       console.log( listTree2(list,0,[]))
    </script>
</body>
</html>